package com.china08.yxyapi.api.comm.upload;

import java.awt.image.BufferedImage;
import java.io.IOException;

import javax.imageio.ImageIO;

import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.china08.yxyapi.api.YxyApiBaseController;
import com.china08.yxyapi.model.YxyApiRespModel;
import com.china08.yxyapi.util.YXCSPUtil;

@CrossOrigin
@RestController
public class UploadFileForErWeiMaController extends YxyApiBaseController {

    @Autowired
    YXCSPUtil yxcspUtil;

    @RequestMapping(value = "/api_yw/comm/upload/img/for/erweima", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public RespModel upLoadWenDoc(@RequestParam(value = "file", required = false) MultipartFile file) throws IOException {
        RespModel respModel = new RespModel();

        try {
            Assert.isTrue((file != null), "未选择文件");

            String name = file.getOriginalFilename();

            // 文件后缀
            String filePostfix = FilenameUtils.getExtension(name);

            String fileType = "png,bmp,jpg,gif,jpeg,JPEG,JPG";

            Assert.isTrue(fileType.contains(filePostfix), "文件类型错误");

            BufferedImage image = ImageIO.read(file.getInputStream());
            int width = image.getWidth();
            int height = image.getHeight();

            Assert.isTrue(width > 0 && width < 561, "请上传宽度不大于560像素，高度不大于80像素的透明背景图片");
            Assert.isTrue(height > 0 && height < 81, "请上传宽度不大于560像素，高度不大于80像素的透明背景图片");

            String url = yxcspUtil.push(file);
            respModel.url = url;
        } //
        catch (Exception e) {
            respModel.success = false;
            respModel.msg = e.getMessage();
        }
        return respModel;
    }

    public static class RespModel extends YxyApiRespModel {
        public String url = "";
        public boolean success = true;
        public String msg;
    }
}
